<?php
namespace app\user\logic\user;

use app\common\exception\LogicException;
use app\user\model\user\Visitor as VisitorModel;

/**
* 访客管理
*/
class Visitor extends VisitorModel
{

    // 添加访客
    public function addVisitor($visit_mid)
    {
        $mid    = request()->mid;
        $time   = time();
        $key    = 'visit_'.$mid.'_'.$visit_mid;
        $cache  = cache($key);
        // 5分钟内不重复记录
        if ($cache) return;
        // 检查已访问
        $visit = $this->mid()->visitor($visit_mid)->findOrEmpty();
        // 添加访问
        if ($visit->isEmpty()) {
            $re = $this::create([
                'user_id'       => $mid,
                'visit_user_id' => $visit_mid
            ]);
            if ( !$re->isEmpty() ) cache($key, $time, 5*60);
        } else {
            $visit->update_time = $time;
            if ( $visit->save() ) cache($key, $time, 5*60);
        }
    }

    // 最近访客列表
    public function recentVisitors($visit_mid, $paginate = true)
    {
        // 被访问用户
        $visit_mid = $visit_mid ? : request()->mid;
        //模型
        $mod = $this->with(['visitor_info'])->visitor($visit_mid)->recent()->field('user_id');
                
        if ( $paginate ) {
            $list = $mod->order('update_time', 'DESC')->paginate($this->getListRows());
        } else {
            $list = $mod->limit(12)->select();
        }

        return $list;
    }

    // 最近访客数量
    public function recentVisitorsNum($visit_mid)
    {
        return $this->visitor($visit_mid)->recent()->count();
    }
}
